package cn.kp.learning.controller;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.kp.learning.model.Roles;
import cn.kp.learning.model.RolesExample;
import cn.kp.learning.service.RolesService;
import cn.kp.learning.util.ResponseUtil;

@Controller
@RequestMapping("/role")
public class RolesController {

	@Resource
	private RolesService rolesService;
	
	@RequestMapping("/rolesAdd")
	public void rolesAdd(HttpServletResponse response,HttpServletRequest request, Roles rl) throws Exception{
		System.out.println("roles adding " + rl.getRolesName());
		JSONObject json=new JSONObject();
		rl.setValid(1);
		RolesExample re = new RolesExample();
		re.createCriteria().andRolesNameEqualTo(rl.getRolesName());
		List<Roles> lt = rolesService.selectRoles(re);
		if(lt.size()>0){
			json.put("success", false);
		}else{
			int result = rolesService.addRoles(rl);
			if(result>0){
				json.put("success", true);
			}else{
				json.put("success", false);
			}
		}		
		try {
			ResponseUtil.write(response, json);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	@RequestMapping("/rolesGet")
	public void rolesGet(HttpServletResponse response,HttpServletRequest request, Roles rl) throws Exception{
		System.out.println("roles adding " + rl.getRolesName());
		rl.setValid(1);
		RolesExample re = new RolesExample();
		
		if(null!=rl){
			if(null!=rl.getRolesName()){
				re.createCriteria().andRolesNameEqualTo(rl.getRolesName());
			}
		}
		List<Roles> lt = rolesService.selectRoles(re);
		
		JSONObject json = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(lt);
		json.put("pages", lt.size()/10+1);
		json.put("total", lt.size());
		json.put("rows", jsonArray);
		
		System.out.println("people Json : " + json.toString());
		try {
			ResponseUtil.write(response, json);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
